import React, { useEffect, useState } from 'react';
import { Table, Form, Select, Button, Typography, Flex, Input, Space } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { apiMSDModuleList, apiMSDModuleFilter, apiMSDModuleRemove } from '../../../services/masterData/module';
import { transformArray } from '../../../utils/commonUtil';
import EditModal from './Components/EditModal';
import DeleteConfirm from '../../Components/DeleteConfirm';

const { Title } = Typography;
const ModuleConfig = () => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  // 分页相关
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalPage, setTotalPage] = useState();
  // list 页面数据
  const [dataList, setDataList] = useState();
  // 下拉框数据
  const [moduleList, setModuleList] = useState([]);
  const [analyticalMList, setAnalyticalMList] = useState([]);
  const [openDrawer, setOpenDrawer] = useState(false);
  const [editType, setEditType] = useState('');
  const [recordData, setRecordData] = useState({});

  const detailClickHandle = (record, type) => {
    setRecordData(record);
    setOpenDrawer(true);
    setEditType(type);
  };
  const deleteClickHandle = (record) => {
    DeleteConfirm({
      t,
      onOk () {
        apiMSDModuleRemove({ id: record.moduleAnalyticalMethodId }).then((res) => {
          if (res?.data?.code === 200) {
            queryList();
          }
        });
      }
    });
  };
  const columns = [
    {
      title: t('common.module'),
      dataIndex: 'moduleName',
      width: 100,
      align: 'center'
    },
    {
      title: t('masterData.analyticalMethod'),
      dataIndex: 'analyticalMethod',
      width: 120,
      align: 'center'
    },
    {
      title: t('common.callMethod'),
      dataIndex: 'callMethod',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.url'),
      dataIndex: 'url',
      width: 120,
      align: 'center'
    },
    {
      title: t('common.request'),
      dataIndex: 'request',
      width: 200,
      align: 'center',
      render: (_, record) => {
        const requestText = record?.request && record?.request.value && JSON.parse(record?.request?.value) || null;
        return (
          <div>{requestText}</div>
        )
      }
    },
    {
      title: t('common.response'),
      dataIndex: 'response',
      width: 200,
      align: 'center',
      render: (_, record) => {
        const responseText = record?.response && record?.response?.value && JSON.parse(record?.response?.value) || null;
        return (
          <div>{responseText}</div>
        )
      }
    },
    {
      title: t('common.remarks'),
      dataIndex: 'remark',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.createdBy'),
      dataIndex: 'createdBy',
      width: 150,
      align: 'center'
    },
    {
      title: t('common.createTime'),
      dataIndex: 'createdTime',
      width: 140,
      align: 'center'
    },
    {
      title: t('common.updateTime'),
      dataIndex: 'updatedTime',
      width: 140,
      align: 'center'
    },
    {
      title: ' ',
      dataIndex: 'operate',
      width: 180,
      align: 'center',
      render: (_, record) => (
        <Space size={2}>
          <Button type="link" className='blue' size='small' onClick={() => detailClickHandle(record, 'view')}>{t('common.view')}</Button>
          <Button type="link" className='blue' size='small' onClick={() => detailClickHandle(record, 'edit')}>{t('common.edit')}</Button>
          <Button type="link" className='red' size='small' onClick={() => deleteClickHandle(record)}>{t('common.delete')}</Button>
        </Space>
      ),
    }
  ];
  const getQueryParams = () => {
    const formData = form.getFieldsValue();
    const params = {
      moduleNames: formData?.moduleNames,
      analyticalMethods: formData?.analyticalMethods,
      createdBy: formData?.createdBy
    };
    return params;
  };
  const serach = () => {
    setCurrentPage(1);
    queryList(1);
  };
  // 获取页面list数据
  const queryList = async (pagination, size) => {
    const params = {
      ...getQueryParams(),
      page: pagination || currentPage,
      limit: size || pageSize
    };
    apiMSDModuleList(params).then((res) => {
      if (res?.data?.code === 200) {
        setDataList(res?.data?.data?.items);
        setTotalPage(res?.data?.data?.total);
      }
    });
  };
  // 调用下拉框api
  const apiSelectAsync = async () => {
    apiMSDModuleFilter().then((res) => {
      if (res?.data?.code === 200) {
        setModuleList(transformArray(res?.data?.data?.moduleNames));
        setAnalyticalMList(transformArray(res?.data?.data?.analyticalMethods));
      }
    });
  };

  useEffect(() => {
    // 正式数据
    queryList();
    // 调用下拉框api
    apiSelectAsync();
  }, [])

  return (
    <>
      <div className='page-title-wrap'>
        <Flex align='center' justify='space-between'>
          <Title className='fontStyleH2' level={2} >{t('common.moduleMethod')}</Title>
          <Button type='primary' onClick={() => {
            setOpenDrawer(true);
            setEditType('new');
          }}>{t('common.new')}</Button>
        </Flex>
      </div>
      <div className='page-content-wrap'>
        <Form form={form} className='filter-wrap'>
          <Flex align='center' gap="middle">
            <Form.Item name="moduleNames"
              label={t('common.module')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={moduleList} />
            </Form.Item>
            <Form.Item name="analyticalMethods"
              label={t('masterData.analyticalMethod')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={analyticalMList} />
            </Form.Item>
            <Form.Item name="createdBy" label={t('common.createdBy')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Input placeholder={t('common.pleaseEnter')} />
            </Form.Item>
            <Button
              className='search-btn'
              type="primary"
              onClick={serach}
              icon={<SearchOutlined style={{ fontSize: 20 }} />}
            />
          </Flex>
        </Form>
        <Table
          columns={columns}
          dataSource={dataList}
          size="small"
          rowKey='moduleAnalyticalMethodId'
          scroll={{ x: 1500, y: 'calc(100vh)' }}
          pagination={{
            total: totalPage,
            current: currentPage,
            pageSize: pageSize,
            onChange: (_crrentPage, _pageSize) => {
              setCurrentPage(_crrentPage);
              setPageSize(_pageSize);
              queryList(_crrentPage, _pageSize);
            },
            pageSizeOptions: [10, 20, 50],
            showSizeChanger: true,
            showTotal: (total) => {
              return t(`common.totalItems`, { total: total });
            },
          }}
        />
      </div>
      {
        openDrawer &&
        <EditModal
          openDrawer={openDrawer}
          setOpenDrawer={setOpenDrawer}
          editSucessFn={() => { queryList() }}
          editType={editType}
          recordData={recordData}
        />
      }
    </>
  )
};

export default ModuleConfig;
